/**
 * Project Name:BGIDXWS
 * File Name:PublicMethod.java
 * Package Name:com.bgi.dx.pub.utils
 * Date:2014-11-24下午05:25:36
 * Copyright (c) 2014, BGI_DX All Rights Reserved.
 *
*/

package com.bgi.uims.pub.utils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.bgi.uims.common.dto.Common;

/**
 * ClassName:PublicMethod <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2014-11-24 下午05:25:36 <br/>
 * @author   fukun
 * @version  
 * @since    JDK 1.7
 * @see 	 
 */
public class PublicMethod {
	//浏览器类型常量
	private final static String IE9="MSIE 9.0";  
    private final static String IE8="MSIE 8.0";  
    private final static String IE7="MSIE 7.0";  
    private final static String IE6="MSIE 6.0";  
    private final static String MAXTHON="Maxthon";  
    private final static String QQ="QQBrowser";  
    private final static String GREEN="GreenBrowser";  
    private final static String SE360="360SE";  
    private final static String FIREFOX="Firefox";  
    private final static String OPERA="Opera";  
    private final static String CHROME="Chrome";  
    private final static String SAFARI="Safari";  
    private final static String OTHER="其它";  

	//通过反射机制获得对象方法的值
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object get(Object o,String name) throws Exception {
		Class cl=o.getClass();
		Method method=cl.getMethod(name);
		return method.invoke(o, new Object[]{});
	}
	//通过反射机制设置对象方法的值
	//eg: this.set(dto, "setName", "123", String.class);
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void set(Object o,String name,Object value,Class... args) throws Exception {
		Class cl=o.getClass();
		Method method=cl.getMethod(name, args);
		method.invoke(o, new Object[]{value});
	}
	//获取IP地址信息
	//request获取IP地址 
	public static String getIpAddr(HttpServletRequest request) {   
	       String ip = request.getHeader("x-forwarded-for");   
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	           ip = request.getHeader("Proxy-Client-IP");   
	       }   
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	           ip = request.getHeader("WL-Proxy-Client-IP");   
	       }   
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	           ip = request.getRemoteAddr();   
	       }   
	       return ip;   
	 }
	
	//request获取用户浏览器    暂时不获取操作系统
	public static String getBrowser(HttpServletRequest request){
		String userAgent = request.getHeader("User-Agent"); 
		
		if(regex(OPERA, userAgent))return OPERA;  
        if(regex(CHROME, userAgent))return CHROME;  
        if(regex(FIREFOX, userAgent))return FIREFOX;  
        if(regex(SAFARI, userAgent))return SAFARI;  
        if(regex(SE360, userAgent))return SE360;  
        if(regex(GREEN,userAgent))return GREEN;  
        if(regex(QQ,userAgent))return QQ;  
        if(regex(MAXTHON, userAgent))return MAXTHON;  
        if(regex(IE9,userAgent))return IE9;  
        if(regex(IE8,userAgent))return IE8;  
        if(regex(IE7,userAgent))return IE7;  
        if(regex(IE6,userAgent))return IE6;  
		
		return OTHER+"\""+userAgent+"\"";
	}
	
	//正则表达式校验浏览器
	private static boolean regex(String regex,String str){  
        Pattern p =Pattern.compile(regex,Pattern.MULTILINE);  
        Matcher m=p.matcher(str);  
        return m.find();
    }  
	
	//根据预产期，获得当前孕周
	public static String getGestationalWeeks(String expectDay)
	{
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		return getGestationalWeeks(expectDay, sdf.format(date));
	}
	
	//指定计算日期(yyyy-MM-dd)，根据预产期，获得孕周
	public static String getGestationalWeeks(String expectDay,String calculateDay)
	{
		//当前时间
		String result=null;
		
		long days=DateUtil.getDays(calculateDay, expectDay, "yyyy-MM-dd");
		//孕天范围1~280，此处为280-孕天的值，所以范围是279~0
		if(days>279){
			days = 279;
		} else if(days<0){
			days = 0;
		}
		
		//多少周
		int week=(int) (days/7);
		int day=(int) (days%7);
		if(day!=0)
		{
			result=40-(week+1)+"W+"+(7-day);
		}
		else
		{
			result=40-week+"W";
		}
		
		return result;
	}
	//根据孕周，计算预产期
	public static String getExpectDay(String gestationalWeeks){
		String result=null;
		//gestationalWeeks  e.g.: 13W+2
		if(gestationalWeeks!=null)
		{
			try{
				String[] arr=gestationalWeeks.split("W\\+");
				if(arr.length==1)
				{
					//只有周
					Integer week=Integer.parseInt(arr[0]);
					result=DateUtil.getBeforeMonthTodayStr("yyyy-MM-dd", 0, (40-week)*7);
				}
				if(arr.length==2 && gestationalWeeks.startsWith("W+"))
				{
					//只有天
					Integer day=Integer.parseInt(arr[1]);
					result=DateUtil.getBeforeMonthTodayStr("yyyy-MM-dd", 0, day);
				}
				else if(arr.length==2 && !gestationalWeeks.startsWith("W+"))
				{
					Integer week=Integer.parseInt(arr[0]);
					Integer day=Integer.parseInt(arr[1]);
					result=DateUtil.getBeforeMonthTodayStr("yyyy-MM-dd", 0, (40-week)*7-day);
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		return result;
	}
	/**
	 * 将孕周字符串转换为中文
	 * @param week 计算孕周的返回值，如：16W,9W+3
	 * return week
	 */
	public static String gestationalWeeksToZh(String week){
		if(StringUtils.isEmpty(week) || week.indexOf("W") < 0){
			return week;
		}
		//不是W结尾有天数,加天
		if(!week.endsWith("W")){
			week = week + "天";
		} 
		//将W换成周
		week = week.replaceAll("W", "周");
		return week;
	}
	
	/**
	 * getGestationalDays:用dateTime与预产期，计算孕天
	 * @author sunhao
	 * @param dateTime
	 * @return 天数
	 */
	public static long getGestationalDays(String dateTime,String expectDay) {
		long days=DateUtil.getDays(dateTime, expectDay, "yyyy-MM-dd");
		return days;
	}
	
	public static void main(String[] args) {
		String res = getGestationalWeeks("2017-01-21");
		System.out.println(res);
	}
	
	/**
	 * 
	 * @Description：  新旧对象对比，insert和delete时newObj==null
	 * @author: WEN
	 * @CreateDate:2015年4月3日 上午11:04:16
	 * @version: V1.0
	 */
	@SuppressWarnings("unchecked")
	public static String[] operationMsg(char method,String modules, Common oldObj, Common newObj) {
		String[] msgStr=new String[5];
		StringBuffer msg=new StringBuffer();
		if(oldObj!=null)
		{
			Map ht1=oldObj.annotationObject();
			if(ht1!=null)
			{
				msgStr[0]=(String) ht1.get("table");
				msgStr[1]=(String) ht1.get("tableId");
				
				switch(method)
				{
					case Constant.INSERT:
						msgStr[2]="1";
						//新增只需要获取对象名称
//						msg.append("[新增->"+ht1.get("object")+"("+ht1.get("describe")+")"+oldObj.getClass().getName()+"]");
						msg.append("新增数据内容为：");
						ht1.remove("table");
						ht1.remove("tableId");
						ht1.remove("object");
						ht1.remove("describe");
						int i=0;
						for(Iterator itr=ht1.keySet().iterator();itr.hasNext();i++)
						{
							String key=(String)itr.next();
							Object o1=(Object)ht1.get(key);
							if(o1==null)
							{
								o1="";
							}
							if(!key.startsWith("SELECT"))  msg.append("  "+key+"为\""+o1.toString()+"\";");
						}
						break;
					case Constant.UPDATE:
						msgStr[2]="3";
						if(newObj!=null)
						{
							Map ht2=newObj.annotationObject();
							if(ht1!=null&&ht2!=null)
							{
//								msg.append("[修改->"+ht1.get("object")+"("+ht1.get("describe")+")"+oldObj.getClass().getName()+"]");
								boolean flag = false;
								msg.append("修改内容为：");
								ht1.remove("table");
								ht1.remove("tableId");
								ht1.remove("object");
								ht1.remove("describe");
								ht2.remove("table");
								ht2.remove("tableId");
								ht2.remove("object");
								ht2.remove("describe");
								for(Iterator itr=ht2.keySet().iterator();itr.hasNext();)
								{
									String key=(String)itr.next();
									Object o1= ht1.get(key);
									Object o2= ht2.get(key);
									if(o1==null && (o2 != null && !"".equals(o2)))
									{
										flag = true;
										msg.append("  "+key+"为\""+o2.toString()+"\";");
									} else  if(o2==null && (o1 != null && !"".equals(o1))) {
										flag = true;
										msg.append(" 去掉了\" "+key+"\" 的值\""+o1.toString()+"\"");
									} else if(o1 != null && o2 != null && !o1.equals(o2) && !key.startsWith("SELECT")) {
										flag = true;
										msg.append("  将"+key+"由\""+o1.toString()+"\"修改成\""+o2.toString()+"\";");
									}
								}
								if(!flag){
									msg.append("空");
								}
							}
						} else {
							msg.append("修改内容为：");
							ht1.remove("table");
							ht1.remove("tableId");
							ht1.remove("object");
							ht1.remove("describe");
							for(Iterator itr=ht1.keySet().iterator();itr.hasNext();)
							{
								String key=(String)itr.next();
								Object o1=(Object)ht1.get(key);
								if(o1==null)
								{
									o1="";
								}
								if(!key.startsWith("SELECT") && !"".equals(o1))  msg.append("  "+key+"为\""+o1.toString()+"\";");
							}
						}
						break;
					case Constant.DELETE:
						msgStr[2]="2";
						//删除需要知道删除名称名称
//						msg.append("[删除->"+ht1.get("object")+"("+ht1.get("describe")+")"+oldObj.getClass().getName()+"]");
						msg.append("删除信息为：");
						ht1.remove("table");
						ht1.remove("tableId");
						ht1.remove("object");
						ht1.remove("describe");
						for(Iterator itr=ht1.keySet().iterator();itr.hasNext();)
						{
							String key=(String)itr.next();
							Object o1=(Object)ht1.get(key);
							if(o1==null)
							{
								o1="";
							}
							if(!key.startsWith("SELECT")) msg.append("  "+key+"为\""+o1.toString()+"\";");
						}
						break;
					case Constant.SELECT:
						msgStr[2]="4";
						//删除需要知道删除名称名称
//						msg.append("[删除->"+ht1.get("object")+"("+ht1.get("describe")+")"+oldObj.getClass().getName()+"]");
						msg.append("查询条件为：");
						ht1.remove("table");
						ht1.remove("tableId");
						ht1.remove("object");
						ht1.remove("describe");
						for(Iterator itr=ht1.keySet().iterator();itr.hasNext();)
						{
							String key=(String)itr.next();
							Object o1=(Object)ht1.get(key);
							if(!(o1==null || "".equals(o1)))
							{
								msg.append("  "+key+"为\""+o1.toString()+"\";");
							}
						}
						if(msg.toString().equals("查询条件为：")){
							msg.append("空");
						}
						break;
					default:
						break;
				}
			}
		}
		msgStr[3]=msg.toString();
		//不需要存太长
		if(msgStr[3].length()>512)
		{
			msgStr[3]=msgStr[3].substring(0, 508)+"....";
		}
		msgStr[4] = modules;
		return msgStr;
	}
}

